package com.qingke.ocr.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.qingke.ocr.pojo.User;

public class OCRDAO {
	
	protected static SessionFactory sf=null;
	protected static Session session=null;
	
	static {
		sf = new Configuration().configure().buildSessionFactory();
		session = sf.openSession();
	}
    
	public <T> List<T> get(Class<T> classType,Map<String,Object> map){
		DetachedCriteria detachCriteria=DetachedCriteria.forClass(classType);
		Criteria criteria=detachCriteria.getExecutableCriteria(session);
		if(map!=null)
			criteria.add(Restrictions.allEq(map));
		@SuppressWarnings("unchecked")
		List<T> list=criteria.list(); 
		return list;
	}
	
    public boolean isUsernameExist(String username){
    	Map<String,Object> map=new HashMap<String, Object>();
    	map.put("username", username);
    	List<User> list=get(User.class,map);
    	if(list.size()>0)
    		return true;
    	else
    		return false;
    }
    
    public User login(String username,String password){
    	Map<String,Object> map=new HashMap<String, Object>();
    	map.put("username", username);
    	map.put("password", password);
    	List<User> list=get(User.class,map);
    	if(list.size()>0)
    		return list.get(0);
    	else
    		return null;
    	
    }
    
    public boolean register(String username,String password,String nickname){
    	if(isUsernameExist(username)){
    		return false;
    	}
    	User user=new User();
    	user.setUsername(username);
    	user.setPassword(password);
    	user.setNickname(nickname);
    	Transaction tx=session.beginTransaction();
		try{
			session.save(user);
			tx.commit();
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
    }
}
